package com.project.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.project.utils.StringUtil;


/**
 * 
 * <p>ClassName: HttpUtils</p>
 * <p>Description: </p>
 * @Author  bsq
 * @Date: 
 */
public class HttpUtils {
	
	public static Logger logger = Logger.getLogger(HttpUtils.class);  

	
	 /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostYiDong(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }   

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("post请求内部错误："+e.getStackTrace());
            result =  "error";
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
                result =  "error";
            }
        }
        return result;
    }  
    public static String sendPost_map(String url, Map<String,Object> mapParams) {
    	PrintWriter out = null;
    	BufferedReader in = null;
    	String result = "";
    	logger.error(url+"----");
    	String param="";
    	try {
    		if (mapParams!=null && mapParams.size()>0){
    			for(Entry<String, Object> entry : mapParams.entrySet()) {
    				if (StringUtils.isBlank(param)){
    					param = param + entry.getKey() + "=" + entry.getValue(); 
    				}else{
    					param = param + "&" + entry.getKey() + "=" + entry.getValue(); 
    				}
    			} 
    		}
    		URL realUrl = new URL(url);
    		// 打开和URL之间的连接
    		URLConnection conn = realUrl.openConnection();
    		// 设置通用的请求属性
    		conn.setRequestProperty("accept", "*/*");
    		conn.setRequestProperty("connection", "Keep-Alive");
    		conn.setRequestProperty("user-agent",
    				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    		// 发送POST请求必须设置如下两行
    		conn.setDoOutput(true);
    		conn.setDoInput(true);
    		// 获取URLConnection对象对应的输出流
    		out = new PrintWriter(conn.getOutputStream());
    		// 发送请求参数
    		out.print(param);
    		// flush输出流的缓冲
    		out.flush();
    		// 定义BufferedReader输入流来读取URL的响应
    		in = new BufferedReader(
    				new InputStreamReader(conn.getInputStream()));
    		String line;
    		while ((line = in.readLine()) != null) {
    			result += line;
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		result =  "error";
    	}
    	//使用finally块来关闭输出流、输入流
    	finally{
    		try{
    			if(out!=null){
    				out.close();
    			}
    			if(in!=null){
    				in.close();
    			}
    		}
    		catch(IOException ex){
    			ex.printStackTrace();
    			result =  "error";
    		}
    	}
    	logger.error(param+"--sendPost--"+result);
    	return result;
    }  
 
    
    public static String getSixRandom(){
		String random = "";
		Random r = new Random();
		for(int i=0;i<6;i++){
			random +=r.nextInt(9);
		}
		return random;
	}
    
	/**
	 * HttpGet方式请求API并返回json数据
	 * @param uri
	 * @param mapParams 参数可以和uri一体，也可以单独设定，切勿一部分在uri上，一部分在mapParams上
	 * @return
	 */
//	public static JSONObject httpGetReturnJson(String uri, Map<String, String> mapParams) {
//
//		//创建返回json对象
//		JSONObject jsonStr = new JSONObject();
//		//参数设定
//		if (mapParams!=null && mapParams.size()>0){
//			if (!uri.endsWith("?")){
//				uri = uri + "?";
//			}
//			for(Entry<String, String> entry : mapParams.entrySet()) {
//				if (uri.endsWith("?")){
//					uri = uri + entry.getKey() + "=" + entry.getValue(); 
//				}else{
//					uri = uri + "&" + entry.getKey() + "=" + entry.getValue(); 
//				}
//			} 
//		}
//		//创建HttpGet对象
//		HttpGet httpGet = new HttpGet(uri);
//		//设置请求和传输超时时间(10s)
//		//HttpHost httpHost = new HttpHost("127.0.0.1", 8787);
//		//HttpHost httpHost = new HttpHost("127.0.0.1", 443);
//		//RequestConfig requestConfig = RequestConfig.custom().setProxy(httpHost).setSocketTimeout(60000).setConnectTimeout(60000).build();
//		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
//		httpGet.setConfig(requestConfig);
//		//创建CloseableHttpClient对象
//		CloseableHttpClient httpClient = HttpClients.createDefault();
//		//创建CloseableHttpResponse对象
//		CloseableHttpResponse httpResponse = null;
//		try {
//			httpResponse = httpClient.execute(httpGet);
//			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//				HttpEntity httpEntity = httpResponse.getEntity();
//				String result = EntityUtils.toString(httpEntity);//取出应答字符串
//				jsonStr = JSONObject.fromObject(result);
//				EntityUtils.consume(httpEntity);
//			}
//			httpClient.close();
//			httpResponse.close();
//			httpGet.releaseConnection();
//		} catch (Exception e) {
//			//  Auto-generated catch block
//			e.printStackTrace();
//			try {
//				httpClient.close();
//				httpResponse.close();
//				httpGet.releaseConnection();
//			} catch (Exception e1) {
//				//  Auto-generated catch block
//				e1.printStackTrace();
//			}
//		}
//		return jsonStr;
//	}
	
	
	/**
	 * 检查API访问是否成功
	 * 
	 * @param object
	 * @return
	 */
	public static boolean isHttpRequestSuccess(JSONObject object) {
		String value = StringUtil.toString(object.get("code"));
		return "0".equals(value);
	}
	/**
	 * 移动请求封装
	 * @param url
	 * @param jsonParam
	 * @return
	 */
	public static String sendPostJson(String url, JSONObject jsonParam) {
    	try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			// 设置请求的header
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);

			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(), "utf-8");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return "";
    }
	/**
	 * 电信请求封装
	 * @param url
	 * @param jsonParam
	 * @return
	 */
	public static String sendPostJsonDx(String url, JSONObject jsonParam) {
    	try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			// 设置请求的header
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);

			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(), "utf-8");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return "";
    }
    
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostWithHeader(String url, String param,String client_csrf_token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("CLIENT-CSRF-TOKEN", client_csrf_token);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
     public static void main(String[] args) {
    	 
    	 //中国电信
    	 String url = "https://open.e.189.cn/api/oauth2/account/userInfo.do";
    	 String clientId = "8024193635";
    	 String timeStamp = "1545117133255";
    	 String accessToken = "0b64dbde53e04b4cb2585e695dec67b9";
    	 String version = "v1.5";
    	 String clientIp = "";
    	 String clientType = "";
    	 String securityId = "";
    	 String authSecurityId = "";
    	 String param = "clientId="+clientId+"&timeStamp="+timeStamp+"&accessToken="+accessToken+"&version="+version+"&clientIp="+clientIp; 
    	 String result = HttpUtils.sendPost(url, param);
    	 System.out.println(result);
//    	 //中国移动
//    	String appkey = "7854B2F35D4137098EF69F2183BC4560";
//    	String version="2.0";
//    	String msgid="20181217160412";
//    	String systemtime="20181217160412111";
//    	String strictcheck="0";
//    	String appid="300011878124";
//    	String token="STsid0000001545035765449RtkZucxUPe15HdwwlVnx5Dh7uv09bB7u";
//    	String sign=ClientMD5SignMake.getMd5StandardString(appid + version + msgid + systemtime + strictcheck + token + appkey).toUpperCase();
//		String url = "https://www.cmpassport.com/unisdk/rsapi/loginTokenValidate";
//		// 设置请求的参数
//		JSONObject jsonParam = new JSONObject();
//		jsonParam.put("version",version);
//		jsonParam.put("msgid",msgid);
//		jsonParam.put("systemtime",systemtime);
//		jsonParam.put("strictcheck",strictcheck);
//		jsonParam.put("appid",appid);
//		jsonParam.put("token",token);
//		jsonParam.put("sign",sign);
//		System.out.println(sendPostJson(url,jsonParam));
	}
}
